import {defineStore} from 'pinia'
import type {UserInfo, UserState} from './helper'
import {defaultSetting, getLocalState, setLocalState} from './helper'

import {chatUserApi} from '@/api/chat_user'

export const useUserStore = defineStore('user-store', {
	state: (): UserState => getLocalState(),
	actions: {
		async getUserData() {
			const data = await chatUserApi.getUserInfo()
			this.updateUserInfo({
				avatar: data.avatarUrl,
				name: data.nickname,
				description: data.description,
				id: data.userId,
				email: data.email,
				canConversationTimes: data.canConversationTimes
			} as UserInfo)
		},

		updateUserInfo(userInfo: Partial<UserInfo>) {
			this.userInfo = {...this.userInfo, ...userInfo}
			this.recordState()
		},

		resetUserInfo() {
			this.userInfo = {...defaultSetting().userInfo}
			this.recordState()
		},

		recordState() {
			setLocalState(this.$state)
		},
	},
})
